<!-- 背景 -->
<template>
  <div class="background-container">
    <div class="cavas-container" ref="screenDom"></div>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import * as THREE from "three";
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader";
import { DRACOLoader } from "three/examples/jsm/loaders/DRACOLoader";
import { gsap } from "gsap";
// 星空背景
import Starrysky from "@/assets/25s.jpg";

let screenDom = ref(null);
onMounted(() => {

  // 创建场景
  let scene = new THREE.Scene();
  // 创建相机
  let camera = new THREE.PerspectiveCamera(
    45,
    window.innerWidth / window.innerHeight,
    0.1,
    100000
  );

  camera.position.set(0, 0, 10);
  // 创建渲染器
  let renderer = new THREE.WebGLRenderer({ antialias: true });
  renderer.setSize(window.innerWidth < 1000 ? 1000 : window.innerWidth, window.innerHeight < 694 ? 694 : window.innerHeight);
  // 将画布添加到页面中
  screenDom.value.appendChild(renderer.domElement);
  // 设置星空背景
  let envTexture = new THREE.TextureLoader().load(Starrysky); // 加载纹理
  envTexture.mapping = THREE.EquirectangularReflectionMapping; // 经纬线映射贴（球形贴图）
  scene.background = envTexture; // 设置场景的背景
  scene.environment = envTexture; // 环境贴图

  function render() {
    requestAnimationFrame(render);
    renderer.render(scene, camera);
  }
  render();

  // 设置解压缩的加载器
  let dracoLoader = new DRACOLoader(); // 加载DRACO压缩模型(加载器)
  dracoLoader.setDecoderPath("/draco/gltf/"); // 路径
  dracoLoader.setDecoderConfig({ type: "js" }); // 表示解码器将以JavaScript的形式加载和使用
  let loader = new GLTFLoader(); // 用于加载jltf文件
  loader.setDRACOLoader(dracoLoader);
  // 加载星球
  loader.load(`/model/moon.glb`, (gitf) => {
    for (let i = 0; i < 10; i++) {
      let moon = gitf.scene.children[0];
      let moonInstace = new THREE.InstancedMesh(
        moon.geometry,
        moon.material,
        100
      );
      for (let i = 0; i < 100; i++) {
        let x = Math.random() * 1000 - 500;
        let y = Math.random() * 1000 - 500;
        let z = Math.random() * 1000 - 500;
        let matrix = new THREE.Matrix4();
        let size = Math.random() * 20 - 8;
        matrix.makeScale(size, size, size);
        matrix.makeTranslation(x, y, z);
        moonInstace.setMatrixAt(i, matrix);
      }
      gsap.to(moonInstace.position, {
        duration: Math.random() * 10 + 2,
        z: -1000,
        ease: "linear",
        repeat: -1,
      });
      scene.add(moonInstace);
    }
  });
});
</script>

<style lang="less" scoped>
    .background-container{
        width: 100%;
        height: 100%;
        .cavas-container{
          width: 100%;
          height: 100%;
          min-height:600px;
        }
    }
</style>